package cn.tao.user.controller;

import cn.tao.base.exception.BusinessException;
import cn.tao.user.domain.LoginInfo;
import cn.tao.user.domain.dto.UserDto;
import cn.tao.user.service.ILoginInfoService;
import cn.tao.user.service.IUserService;
import cn.tao.utils.AjaxResult;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RestController;

import java.util.HashMap;
import java.util.Map;
import java.util.UUID;
import java.util.concurrent.TimeUnit;

@RestController
public class AccountController {

    @Autowired
    private IUserService userService;

    @Autowired
    private ILoginInfoService loginInfoService;

    @Autowired
    private RedisTemplate redisTemplate;

    /**
     * 用户注册
     * @param userDto
     * @return
     */
    @PostMapping("/register")
    public AjaxResult register(@RequestBody UserDto userDto){

        try {
            userService.register(userDto);
            return AjaxResult.me();
        } catch (BusinessException e) {
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }

    /**
     * 用户登录
     * @param userDto
     * @return
     */
    @PostMapping("/login")
    public AjaxResult login(@RequestBody UserDto userDto){

        try {
            //数据验证完，得到的用户，然后把它放入redis中
            LoginInfo loginInfo = loginInfoService.login(userDto);
            //获取token
            String token = UUID.randomUUID().toString();
            //把token当作key 用户login当作value 设置过期时间30分钟
            //此时启动有问题 报错  问题：redis存储数据时的序列化原因 解决：Baesdomain实现一个serializable
            redisTemplate.opsForValue().set(token,loginInfo,30, TimeUnit.MINUTES);

            //把token和loginInfo返回给前端
            Map<String, Object> map = new HashMap<String, Object>();
            map.put("token",token);
            //把密码和盐清空
            loginInfo.setPassword("");
            loginInfo.setSalt("");
            map.put("loginInfo",loginInfo);
            return AjaxResult.me().setResultObj(map);
        } catch (BusinessException e) {
            return AjaxResult.me().setMessage(e.getMessage());
        }

    }



}
